var area = require('../../data/area.js')
var areaInfo = [];//所有省市区县数据
var provinces = [];//省
var citys = [];//城市
var countys = [];//区县
var index = [0, 0, 0];
var cellId;
var t = 0;
var show = false;
var moveY = 200;

Page({
  data: {
    id: '',//地址id
    userId: '',//用户id
    show: show,
    provinces: provinces,
    citys: citys,
    countys: countys,
    value: [0, 0, 0],
    receiver: '',//收货人
    phone: '',//电话
    phoneTip: '',//电话tip
    street: '',//街道
    detail: '',//详细地址
  },
  onLoad: function (options) {
    console.log("jiazai")
    console.log(options)
    cellId = options.cellId;
    var that = this;
    var date = new Date()
    console.log(date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日");

    //获取用户id
    let userId = wx.getStorageSync('userId');
    console.log(userId)
    that.setData({
      userId: userId,
    })
    //接受微信地址
    // if (options.wx === '1'){
    //   that.setData({
    //     receiver: options.receiver,
    //     phone: options.phone,
    //     city: options.city,
    //     county: options.county,
    //     province: options.province,
    //     street: options.detail,
    //     detail: options.detail
    //   });
    // }
    
    if (options.id !== undefined) {
      that.setData({
        id: options.id
      })
      this.getAddressDetail();
    }

    //获取省市区县数据
    area.getAreaInfo(function (arr) {
      areaInfo = arr;
      //获取省份数据
      getProvinceData(that);
    });

  },


  /* 获取收货人 */
  getReceiver: function(e){
    let receiver = e.detail.value;
    this.setData({
      receiver: receiver
    })
  },

  /* 获取手机号 */
  getPhone: function (e) {
    let phone = e.detail.value;
    let myreg = /^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$/;
    if (phone.length == 0) {
      this.setData({
        phoneTip: '手机号不能为空'
      })
    } else if (!myreg.test(phone)) {
      this.setData({
        phoneTip: '请检查您的手机号是否有误'
      })
    } else {
      this.setData({
        phoneTip: '',
        phone: phone
      })
    }
  },

  /* 获取街道 */
  getStreet: function (e) {
    let street = e.detail.value;
    this.setData({
      street: street
    })
  },

  /* 获取详细地址 */
  getDetail: function (e) {
    let detail = e.detail.value;
    this.setData({
      detail: detail
    })
  },

  /* 保存地址 */
  save: function () {
    var url = wx.getStorageSync("config");
    let that = this;
    let receiver = that.data.receiver;
    let phone = that.data.phone;
    let street = that.data.street;
    let detail = that.data.detail;
    let province = that.data.province;
    let city = that.data.city;
    let country = that.data.county;
    let userId = that.data.userId;
    let id = that.data.id;
    let myreg = /^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$/;

    if (!myreg.test(phone)){
      wx.showModal({
        title: '手机号有误！',
        showCancel: false, //是否显示取消按钮
        success: function (res) {
          if (res.confirm) { //这里是点击了确定以后
          }
        }
      })
    }
    else if (receiver === '' || phone === '' || street === '' || detail === '' || province === '' || city   === '' || country === ''){
      wx.showModal({
        title: '不能为空！',
        showCancel: false, //是否显示取消按钮
        success: function (res) {
          if (res.confirm) { //这里是点击了确定以后
          }
        }
      })
    }else{
      if (id !== '') {
        wx.request({
          url: url.service.homeUrl + "/huiguniang/address/update",
          method: "POST",
          header: { 'Content-Type': 'application/x-www-form-urlencoded' },
          data: {
            receiver: receiver,
            id: id,
            phone: phone,
            street: street,
            detail: detail,
            province: province,
            city: city,
            country: country,
            openId: userId
          },
          success: function (res) {
            console.log(res)
            if (res.data.status.returnCode === 1) {
              wx.showModal({
                title: '保存成功！',
                showCancel: false, //是否显示取消按钮
                success: function (res) {
                  if (res.confirm) { //这里是点击了确定以后
                    wx.navigateBack({
                      // delta: 1
                      url: "/pages/addresses/addresses",
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            wx.showModal({
              title: '保存失败，请重试！',
              showCancel: false, //是否显示取消按钮
              success: function (res) {
                if (res.confirm) { //这里是点击了确定以后

                }
              }
            })
          },
          complete: function (res) { },
        })
      } else {
        wx.request({
          url: url.service.homeUrl + "/huiguniang/address/add",
          method: "POST",
          header: { "Content-Type": "application/x-www-form-urlencoded" },
          data: {
            receiver: receiver,
            phone: phone,
            street: street,
            detail: detail,
            province: province,
            city: city,
            country: country,
            openId: userId
          },
          success: function (res) {
            console.log(res)
            if (res.data.status.returnCode === 1) {
              wx.showModal({
                title: '保存成功！',
                showCancel: false, //是否显示取消按钮
                success: function (res) {
                  if (res.confirm) { //这里是点击了确定以后
                    wx.navigateBack({
                      delta: 1
                      // url: "/pages/addresses/addresses",
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            wx.showModal({
              title: '保存失败，请重试！',
              showCancel: false, //是否显示取消按钮
              success: function (res) {
                if (res.confirm) { //这里是点击了确定以后

                }
              }
            })
          },
          complete: function (res) { },
        })
      }
    }
  },

  /* 获取当前地址信息 */
  getAddressDetail: function() {
    var url = wx.getStorageSync("config")
    let that = this;
    let id = that.data.id;
    let userId = that.data.userId;
    console.log(id)
    wx.request({
      url: url.service.homeUrl + "/huiguniang/address/fetch?id=" + id + "&openId=" + userId,
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: function (res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          let addressDetail = res.data.result;
          that.setData({
            receiver: addressDetail.receiver,
            phone: addressDetail.phone,
            street: addressDetail.street,
            detail: addressDetail.detail,
            province: addressDetail.province,
            city: addressDetail.city,
            county: addressDetail.country
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  //滑动事件
  bindChange: function (e) {
    var val = e.detail.value

    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      getCityArr(val[0], this);//获取地级市数据
      getCountyInfo(val[0], val[1], this);//获取区县数据
    } else {    //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], this);//获取区县数据
      }
    }
    index = val;

    console.log(index + " => " + val);

    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      province: provinces[val[0]].name,
      city: citys[val[1]].name,
      county: countys[val[2]].name
    })

  },
  
  // ------------------- 分割线 --------------------
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    }
    )
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },
  //移动按钮点击事件
  translate: function (e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    // this.animation.translate(arr[0], arr[1]).step();
    animationEvents(this, moveY, show);

  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    console.log(e);
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this, moveY, show);

  },
  //页面滑至底部事件
  onReachBottom: function () {
    // Do something when page reach bottom.
  }
})

//动画事件
function animationEvents(that, moveY, show) {
  console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  }
  )
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })

}

// ---------------- 分割线 ---------------- 

//获取省份数据
function getProvinceData(that) {
  var s;
  provinces = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    s = areaInfo[i];
    if (s.di == "00" && s.xian == "00") {
      provinces[num] = s;
      num++;
    }
  }
  that.setData({
    provinces: provinces
  })

  //初始化调一次
  getCityArr(0, that);
  getCountyInfo(0, 0, that);
  that.setData({
    province: "北京市",
    city: "市辖区",
    county: "东城区",
  })

}

// 获取地级市数据
function getCityArr(count, that) {
  var c;
  citys = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.xian == "00" && c.sheng == provinces[count].sheng && c.di != "00") {
      citys[num] = c;
      num++;
    }
  }
  if (citys.length == 0) {
    citys[0] = { name: '' };
  }

  that.setData({
    city: "",
    citys: citys,
    value: [count, 0, 0]
  })
}

// 获取区县数据
function getCountyInfo(column0, column1, that) {
  var c;
  countys = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.xian != "00" && c.sheng == provinces[column0].sheng && c.di == citys[column1].di) {
      countys[num] = c;
      num++;
    }
  }
  if (countys.length == 0) {
    countys[0] = { name: '' };
  }
  that.setData({
    county: "",
    countys: countys,
    value: [column0, column1, 0]
  })
}